package com.moyoutian.leetcode;

/**
 * 100. 相同的树
 * <p>
 * 给你两棵二叉树的根节点 p 和 q ，编写一个函数来检验这两棵树是否相同。
 * <p>
 * 如果两个树在结构上相同，并且节点具有相同的值，则认为它们是相同的。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：p = [1,2,3], q = [1,2,3]
 * 输出：true
 * <p>
 * 示例 2：
 * <p>
 * 输入：p = [1,2], q = [1,null,2]
 * 输出：false
 * <p>
 * 示例 3：
 * <p>
 * 输入：p = [1,2,1], q = [1,1,2]
 * 输出：false
 * <p>
 * <p>
 * <p>
 * 提示：
 * <p>
 * 两棵树上的节点数目都在范围 [0, 100] 内
 * -104 <= Node.val <= 104
 */
public class Demo100 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode p = new TreeNode(1);
        p.left = new TreeNode(1);
        TreeNode q = new TreeNode(1);
        q.left = new TreeNode(2);
        System.out.println(isSameTree(p, q));
    }

    /**
     * 双指针
     */
    public static boolean isSameTree(TreeNode p, TreeNode q) {

        TreeNode pTemp = p;
        TreeNode qTemp = q;
        while (pTemp != null && qTemp != null) {
            if (pTemp.left != qTemp.left) {
                return false;
            }
            pTemp = pTemp.left;
            qTemp = qTemp.left;
        }


        while (true) {
            if (pTemp.right != qTemp.right) {
                return false;
            }
            pTemp = pTemp.right;
            qTemp = qTemp.right;
        }
    }

    public static boolean isSameTree1(TreeNode p, TreeNode q) {
        if (p != null && q != null && p.val == q.val) {
            return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        } else {
            if (p == null && q == null) {
                return true;
            } else {
                return false;
            }
        }
    }

}
